#include "sensorthread.h"

SensorThread::SensorThread( QObject *parent ) :
	QThread( parent )
{
	QFile gpioFile( "/sys/class/gpio/export" );
	if( gpioFile.open( QIODevice::ReadWrite ) )
	{
		gpioFile.seek( 0 );
		gpioFile.write( "150" );
		gpioFile.close();
	}

	QFile gpioLED( "/sys/class/gpio/gpio150/direction" );
	if( gpioLED.open( QIODevice::ReadWrite ) )
	{
		gpioLED.seek( 0 );
		gpioLED.write( "out" );
		gpioLED.close();
	}

	gpioValue = new QFile( "/sys/class/gpio/gpio150/value" );
	if( gpioValue->open( QIODevice::ReadWrite ) )
	{
		gpioValue->seek( 0 );
		gpioValue->write( "1" );
		gpioValue->close();
	}
}

SensorThread::~SensorThread()
{
	QFile gpioFile( "/sys/class/gpio/unexport" );
	if( gpioFile.open( QIODevice::ReadWrite ) )
	{
		gpioFile.seek( 0 );
		gpioFile.write( "150" );
		gpioFile.close();
	}
	delete gpioValue;
}

void SensorThread::run()
{
	bool toggle = false;
	while( true )
	{
		if( gpioValue->open( QIODevice::ReadWrite ) )
		{
			gpioValue->seek( 0 );
			gpioValue->write( toggle == true ? "1" : "0" );
			gpioValue->close();
			toggle = !toggle;
		}
		sleep( 1 );
	}
}
